import { useLoading } from '/@lib/hooks/useLoading.ts'

type Api = () => Promise<any>

export function useRequestWithLoading(isLoading = false) {
  // export function useRequestWithLoading(api: Api, isLoading = true) {
  const { loading, showLoading, hideLoading } = useLoading(isLoading)
  const requestWithLoading = async (api: Api, callback?: (res: any) => Promise<void>) => {
    try {
      showLoading()
      const res = await api()
      if (callback) {
        await callback(res)
      }
      return res
    } finally {
      hideLoading()
    }
  }

  return { loading, requestWithLoading, showLoading, hideLoading }
}
